﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Library.Data.Security.Encryption;

namespace UnigenReport.Form
{
    public partial class ucShippingRequestEdit : UserControl
    {
        private ShippingRequest refData;
        private UnigenDataContext db;
        private bool action;//True: Add, False: Update
        private int maxQuantity = 0;

        #region Thiết lập

        public ucShippingRequestEdit()
        {
            InitializeComponent();
            //Phân quyền
            if (Variables.UserRoleID == 0) btnSave.Enabled = false;

            SetEvent();

            action = true;
            txtCreatedDate.Value = DateTime.Now;
        }

        /// <summary>
        /// Hàm show ra ngoài cho việc update
        /// </summary>
        /// <param name="refData"></param>
        /// <returns></returns>
        public ucShippingRequestEdit ForUpdate(ShippingRequest obj)
        {
            refData = obj;
            action = false;
            return this;
        }

        /// <summary>
        /// Khai báo các sự kiện
        /// </summary>
        private void SetEvent()
        {
            Load += OnLoad;
            this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            this.cboAddress.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cboAddress_KeyDown);
            this.cboWO.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cboWO_KeyDown);
            this.cboAddress.SelectedIndexChanged += new System.EventHandler(this.cboAddress_SelectedIndexChanged);
        }
        
        /// <summary>
        /// Hàm load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoad(object sender, EventArgs e)
        {
            //Load default
            SetDefault();
        }
        
        /// <summary>
        /// Thiết lập các giá trị mặc định của form
        /// </summary>
        private void SetDefault()
        {
            //Address
            db = new UnigenDataContext();
            sourceAddress.DataSource = db.ShipAddresses.Where(p => p.Active == true && p.Type == 1).OrderBy(p=>p.Name).ToList();                       

            //Bind dữ liệu chính
            BindData();
        }

        /// <summary>
        /// Lấy dữ liệu chính
        /// </summary>
        private void BindData()
        {
            try
            {
                //Data bind
                if (refData != null)
                {
                    db = new UnigenDataContext();
                    pnlTitle.Text = "EDITING SHIPPING REQUEST";

                    //WO
                    var selectedWo = db.WorldOrders.SingleOrDefault(p=>p.WOId == refData.WOId);
                    if (selectedWo != null)
                        sourceWO.DataSource = selectedWo;

                    //address
                    var selectedAdd = (sourceAddress.DataSource as List<ShipAddress>).SingleOrDefault(p => p.ShipAddressId == refData.ShipAddressId);
                    if (selectedAdd != null)
                    {
                        cboAddress.SelectedValue = selectedAdd.ShipAddressId;
                        txtAddress.Text = selectedAdd.Address;
                    }

                    txtQuantity.Value = refData.Quantity ?? 0;
                    txtCreatedDate.Value = refData.CreatedDate ?? DateTime.Now;
                    CalMaxQty();
                    if (refData.Status == 1)
                    {
                        btnSave.Enabled = false;
                        pnlTitle.Text = "VIEW SHIPPING REQUEST \n (Cannot edit because this request has been closed)";                        
                    }
                    if (refData.Active == true && Variables.UserRoleID == 1)
                    {
                        btnSave.Enabled = false;
                        pnlTitle.Text = "VIEW SHIPPING REQUEST \n (Cannot edit because this request has been confirmed)";
                    }
                }
                else
                    pnlTitle.Text = "ADD NEW SHIPPING REQUEST";
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("BindData - " + ex.Message);
            }
        }

        /// <summary>
        /// Tính số nhập tối đa
        /// </summary>
        private void CalMaxQty()
        {
            //lbl max quantity
            var wo = sourceWO.Current as WorldOrder;
            if (wo != null)
            {
                int totalQty = (int)(wo.Ordered - wo.Debit);
                int requestedQty = Convert.ToInt32(db.ShippingRequests.Where(p => p.WOId == wo.WOId).Sum(p => p.Quantity) ?? 0);
                maxQuantity = refData == null ? (totalQty - requestedQty) : (totalQty - requestedQty + (int)(refData.Quantity ?? 0));

                lblMaxQuantity.Text = maxQuantity.ToString("N0") + " / " + totalQty.ToString("N0");
                txtQuantity.Maximum = maxQuantity;
                txtQuantity.Value = txtQuantity.Value > maxQuantity ? maxQuantity : txtQuantity.Value;
            }
        }
        #endregion

        #region Hàm

        private void Save()
        {
            try
            {
                var wo = Convert.ToInt32(cboWO.SelectedValue ?? 0);
                var address = Convert.ToInt32(cboAddress.SelectedValue ?? 0);
                var quantity = (int?)txtQuantity.Value;
                var createdDate = txtCreatedDate.Value;
                var active = Variables.UserRoleID == 1 ? false : true;

                #region Check valid
                if (wo == 0)
                {
                    Common.ShowNoticeMess("WO required!");
                    return;
                }
                if (address == 0)
                {
                    Common.ShowNoticeMess("Address required!");
                    return;
                }
                if (quantity == 0)
                {
                    Common.ShowNoticeMess("Quantity required!");
                    return;
                }
                #endregion

                db = new UnigenDataContext();
                var p = new ShippingRequest();
                if (action)//Thêm mới
                {
                    p.Status = 0;
                    p.WOId = wo;
                    p.Quantity = quantity;
                    p.ShipAddressId = address;
                    p.CreatedDate = createdDate;
                    p.Active = active;

                    //Thêm thông tin
                    db.ShippingRequests.InsertOnSubmit(p);
                }
                else
                {
                    //Cập nhật thông tin
                    p = db.ShippingRequests.SingleOrDefault(pt => pt.RequestId == refData.RequestId);
                    if (p != null)
                    {
                        p.Status = 0;
                        p.WOId = wo;
                        p.Quantity = quantity;
                        p.ShipAddressId = address;
                        p.CreatedDate = createdDate;
                    }
                }

                //Xác nhận
                db.SubmitChanges();

                //Thông báo
                this.ParentForm.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Save - " + ex.Message);
            }
        }

        #endregion

        #region Sự kiện

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
           if (keyData == Keys.Enter && btnSave.Enabled == true && !btnSave.Focused && !btnCancel.Focused && (cboWO.FocusedElement == null) && (cboAddress.FocusedElement == null))
            {
                Save();
            }
            if (keyData == Keys.Escape)
            {
                this.ParentForm.DialogResult = DialogResult.Cancel;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void cboWO_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    //WO
                    var wo = cboWO.Text.Trim();
                    db = new UnigenDataContext();
                    if (!String.IsNullOrEmpty(wo))
                    {
                        var selectedWo = db.WorldOrders.SingleOrDefault(p => p.WO == wo && p.Active == true);
                        if (selectedWo != null)
                        {
                            sourceWO.DataSource = selectedWo;
                            CalMaxQty();
                        }
                        else
                        {
                            Common.ShowNoticeMess("Cannot found the input WO");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("cboWO_KeyDown - " + ex.Message);
            }
        }

        private void cboAddress_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    var selectedAdd = new ShipAddress();
                    var addId = 0;
                    if (int.TryParse(cboAddress.Text.Trim(), out addId))
                        selectedAdd = (sourceAddress.DataSource as List<ShipAddress>).SingleOrDefault(p => p.ShipAddressId == addId);
                    else
                        selectedAdd = (sourceAddress.DataSource as List<ShipAddress>).FirstOrDefault(p => p.Name.Contains(cboAddress.Text.Trim()));

                    if (selectedAdd != null)
                    {
                        cboAddress.SelectedValue = selectedAdd.ShipAddressId;
                        txtAddress.Text = selectedAdd.Address;
                    }
                    else
                    {
                        cboAddress.SelectedIndex = 0;
                        txtAddress.Text = String.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("cboAddress_KeyDown - " + ex.Message);
            }
        }

        private void cboAddress_SelectedIndexChanged(object sender, EventArgs e)
        {
            try 
            {
                var currentAdd = sourceAddress.Current as ShipAddress;
                txtAddress.Text = currentAdd.Address;
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("cboAddress_SelectedIndexChanged - " + ex.Message);
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.ParentForm.DialogResult = DialogResult.Cancel;
        }

        #endregion
    }
}
